#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import glob
import _mysql, _mysql_exceptions

def connect_to_base_dicts(db='dbwww58com_base_dicts'):
    host = '10.5.20.16'
    port = 58885
    user = 'ec_stat'
    passwd = 'L#c8UM5RGh5C'
    dbh = _mysql.connect(host, user, passwd, db, port)
    return dbh

def insertinto(dbh, tablename, field, value,filename,dryrun=False):
    if len(field) != len(value):
        print 'the len of field is not equal len of value:'
        print '*' * 60
        print field
        print value
        print '*' * 60
        return False
    q = "INSERT INTO %s (%s) VALUES (%s);" % (tablename, ','.join(field), ','.join(map(lambda x: "'" + str(x) + "'", value)))
    if dryrun:
        print q
        return True
    try:
        dbh.query(q)
    except _mysql_exceptions.IntegrityError, e:
        with open('errorlog.txt','a') as errorfile:
            errorfile.write(filename+":"+','.join(value)+'\n')
        print str(e).decode('UTF-8')
        return False
    return True

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'usage: %s tablename dataDirectory!' % (sys.argv[0])
        sys.exit(1)
    tablename=sys.argv[1]
    filepath = sys.argv[2]
    field=["stat_date", "local_id","dispcity1", "dispcity2",
            "dispcity3", "cate_id","belong_cate1", "belong_cate2", "total_info_count",
            "total_info_users", "valid_info_count", "valid_info_users",
            "new_info_count", "new_info_users", "modify_info_count",
            "modify_info_users", "refresh_info_count", "refresh_info_users",
            "new_valid_info_count", "new_valid_info_users",
            "ordinary_valid_info_count", "ordinary_valid_info_users",
            "ordinary_new_info_count", "ordinary_new_info_users",
            "ordinary_modify_info_count", "ordinary_modify_info_users",
            "ordinary_refresh_info_count", "ordinary_refresh_info_users",
            "ordinary_new_valid_info_count", "ordinary_new_valid_info_users",
            "vip_valid_info_count", "vip_valid_info_users",
            "vip_new_info_count", "vip_new_info_users",
            "vip_modify_info_count", "vip_modify_info_users",
            "vip_refresh_info_count", "vip_refresh_info_users",
            "vip_new_valid_info_count", "vip_new_valid_info_users"]
    conn=connect_to_base_dicts('test')
    with open(filepath) as file:
        for line in file:
            values = line.strip().split(',')
            insertinto(conn, tablename, field, values,filepath)
    conn.close()
    sys.exit(0)
